package org.springframework.samples.countries.web.translate;

import java.util.List;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.EmptyVisitor;

import pikes.ecma.FunctionDeclaration;
import pikes.ecma.SourceElement;

public class PageMemberFunctionTranslator extends EmptyVisitor implements TranslationResultProcessor {

	private Behaviour behaviour = null;

	private String currentMethodName = null;

	private boolean translateEmptyBodyAsReturn = false;

	public PageMemberFunctionTranslator(Behaviour behaviour) {
		this(behaviour, false);
	}

	public PageMemberFunctionTranslator(Behaviour behaviour, boolean translateEmptyBodyAsReturn) {
		super();
		this.behaviour = behaviour;
		this.translateEmptyBodyAsReturn = translateEmptyBodyAsReturn;
	}

	@Override
	public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
		this.currentMethodName = name;
		Type[] parameterTypes = Type.getArgumentTypes(desc);
		return new AnnotationCheckingTranslator(new MethodBlockTranslator(name, parameterTypes.length, this,
				translateEmptyBodyAsReturn));
	}

	public void processResult(List<String> parameters, SourceElement functionBody) {
		FunctionDeclaration functionDeclaration = new FunctionDeclaration(currentMethodName);

		for (String parameter : parameters) {
			functionDeclaration.add(parameter);
		}

		functionDeclaration.add(functionBody);
		behaviour.add(functionDeclaration);
		currentMethodName = null;
	}

}